package com.guojiaming.shop.service;

import com.guojiaming.shop.dao.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author vivo
 */
@Service
@Transactional(rollbackFor = {Exception.class})
@SuppressWarnings("unused")
public class DatabaseService {
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AfterSaleMapper afterSaleMapper;
    @Resource
    private ImageFileMapper imageFileMapper;
    @Resource
    private SalesMapper salesMapper;
    @Resource
    private GoodsMapper goodsMapper;

    private Logger logger = LoggerFactory.getLogger(MemberMapper.class);
    private static final String TAG = "[A-Z]";

    public Boolean init() throws Exception {
        return initTables();
    }

    private boolean initTables() throws Exception {
        boolean result = false;
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (isSubClass(field.getType())) {
                //强转为BaseMapper
                BaseMapper mapper = (BaseMapper) field.get(this);
                //获取去掉Mapper后缀的类名
                String tableName = field.getType().getSimpleName().replace("Mapper", "");
                //把驼峰转变为下划线
                StringBuffer underline = underline(new StringBuffer(tableName));
                //添加表名头 t
                underline.insert(0, "t");
                //检查表是否存在小于等于0为不存在
                String createTableName = underline.toString().toUpperCase();
                int table = mapper.isExistTable(underline.toString());
                if (table <= 0) {
                    //如果不存在调用建表的方法
                    Method createTable = field.getType().getMethod("createTable", String.class);
                    createTable.invoke(mapper, createTableName);
                    logger.info("创建了表:" + createTableName);
                    result = true;
                } else {
                    logger.info("表已经存在:" + createTableName);
                }
            }
        }
        return result;
    }

    private boolean isSubClass(Class subClass) {
        try {
            subClass.asSubclass(BaseMapper.class);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private StringBuffer underline(StringBuffer str) {
        Pattern pattern = Pattern.compile(TAG);
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer(str);
        if (matcher.find()) {
            sb = new StringBuffer();
            //将当前匹配子串替换为指定字符串，并且将替换后的子串以及其之前到上次匹配子串之后的字符串段添加到一个StringBuffer对象里。
            //正则之前的字符和被替换的字符
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
            //把之后的也添加到StringBuffer对象里
            matcher.appendTail(sb);
        } else {
            return sb;
        }
        return underline(sb);
    }
}
